#import "YQPLoginModel.h"
#import "MuYing-Bridging-Header.h"
#import "BRPickerView.h"
#import "MYLoginBaseVC.h"
#import "MYRegisterSetPasswordVC.h"
#import "MYRegisterFindPasswordVC.h"
#import "YQMYTabBarBaseViewController.h"
#import "MYAgreementVC.h"
#import <FBSDKLoginManager.h>
#import <WXApi.h>
#import <FBSDKProfile.h>
#import <FBSDKAccessToken.h>
#import <FBSDKGraphRequest.h>
#import <FBSDKLoginManagerLoginResult.h>
@interface MYLoginBaseVC ()<UITextFieldDelegate,WXApiDelegate>

@property (nonatomic,strong) Calculagraph *codeTimer;
@property (nonatomic) BOOL status;
@property (nonatomic) BOOL isHidden;
@end

@implementation MYLoginBaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectOperateType = 2;
    if ([YQPUserTool account].token) {
        [self getVersion];

    }
}

- (void)getVersion
{
    NSString *version=[[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    [YQPNetWorkingManager sendGetRequest:kGET_SLIDESHOW_VERSION_URL parameters:nil success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        self.isHidden=YES;
        NSUInteger result=[version compare:responseObject.data[@"version"]];
        if (result>0) {
            self.status=YES;
        }
        else
        {
            self.status=NO;
        }
        [self.listTableView reloadData];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
    
}

#pragma mark - UITextFieldDelegate代理，登录输入手机号后收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    [self.view endEditing:YES];
    return YES;
}

-(void)setupView {
    [super setupView];
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-168-kHeight_Botton_SafeArea);
    [self.listTableView registerNib:[UINib nibWithNibName:@"MYLoginThirdPartyFooterView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MYLoginThirdPartyFooterView"];
    [self.listTableView registerClass:[MYLoginBaseBtnCell class] forCellReuseIdentifier:@"MYLoginBaseBtnCell"];
    [self.listTableView registerClass:[MYLoginBaseTextFieldCell class] forCellReuseIdentifier:@"MYLoginBaseTextFieldCell"];
    [self.listTableView registerClass:[MYLoginBaseTextFieldCodeCell class] forCellReuseIdentifier:@"MYLoginBaseTextFieldCodeCell"];
    [self.listTableView registerClass:[MYLoginBaseTextPasswordCell class] forCellReuseIdentifier:@"MYLoginBaseTextPasswordCell"];
    
    [self.listTableView registerNib:[UINib nibWithNibName:@"MYLoginBaseForgetCell" bundle:nil] forCellReuseIdentifier:@"MYLoginBaseForgetCell"];
    [self.listTableView registerClass:[MYLoginBaseTextFieldPhoneCell class] forCellReuseIdentifier:@"MYLoginBaseTextFieldPhoneCell"];
    
}

// 返回列表视图
// 如果列表是VC，就返回VC.view
// 如果列表是View，就返回View自己
- (UIView *)listView {
    return self.view;
}
- (UIScrollView *)listScrollView {
    return self.listTableView;
}


#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        MYLoginBaseBtnCell *loginCell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseBtnCell"];
        [loginCell.loginBtn setBackgroundColor:HexColor(0x79C4C7)];
        [loginCell.loginBtn setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
        [loginCell.loginBtn addTarget:self action:@selector(loginOrRegisterAction:) forControlEvents:(UIControlEventTouchUpInside)];

        if (self.showType == LoginOrRegisterTypeLogin) {
            
            [loginCell.loginBtn setTitle:kYQLS(@"登录") forState:(UIControlStateNormal)];
//            [loginCell.loginBtn addTapAction:^(id  _Nonnull sender) {
//                [self loginOnHttpApi:self.showType];
//
//            }];
        }else if (self.showType == LoginOrRegisterTypeRegister){
            [loginCell.loginBtn setTitle:kYQLS(@"注册") forState:(UIControlStateNormal)];
        }
        
        return loginCell;
    }else if (indexPath.row == 4) {
        MYLoginBaseBtnCell *loginTypeCell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseBtnCell"];
        [loginTypeCell.loginBtn setBackgroundColor:UIColor.whiteColor];
        [loginTypeCell.loginBtn setTitleColor:HexColor(0x79C4C7) forState:(UIControlStateNormal)];
        [loginTypeCell.loginBtn addTarget:self action:@selector(selectOperateTypeAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        if (self.showType == LoginOrRegisterTypeLogin) {
            if (self.selectOperateType == 1) {
                [loginTypeCell.loginBtn setTitle:kYQLS(@"帐号登录") forState:(UIControlStateNormal)];
            }else{
                [loginTypeCell.loginBtn setTitle:kYQLS(@"手机号登录") forState:(UIControlStateNormal)];
            }
        }else{
            if (self.selectOperateType == 1) {
                [loginTypeCell.loginBtn setTitle:kYQLS(@"邮箱注册") forState:(UIControlStateNormal)];
            }else{
                [loginTypeCell.loginBtn setTitle:kYQLS(@"手机号注册") forState:(UIControlStateNormal)];
            }
        }

        
        return loginTypeCell;
    }else if (indexPath.row == 2) {
        MYLoginBaseForgetCell *fortgetCell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseForgetCell"];
        if (self.showType == LoginOrRegisterTypeLogin) {
            fortgetCell.forgetBtn.hidden = NO;
            ws(self);
            [fortgetCell.forgetBtn addTapAction:^(id  _Nonnull sender) {
                MYRegisterFindPasswordVC *findVC = [[MYRegisterFindPasswordVC alloc] init];
                [weakself.navigationController pushViewController:findVC animated:true];
            }];
        }else{
            fortgetCell.forgetBtn.hidden = YES;
        }
        return fortgetCell;
    }
    MYLoginBaseTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYLoginBaseTextFieldCell"];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4 || indexPath.row == 3) {
        return 68;
    }else if (indexPath.row == 2){
        return 57;
    }
    return 57;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
      
    
    MYLoginThirdPartyFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYLoginThirdPartyFooterView"];
    if (self.isHidden)
    {
        if (self.status) {
            footerView.facebookLoginBtn.hidden=YES;
            footerView.wechatLoginBtn.hidden=YES;
            footerView.agreementBtn.hidden=NO;
        }
        else
        {
            footerView.facebookLoginBtn.hidden=NO;
            footerView.wechatLoginBtn.hidden=NO;
            footerView.agreementBtn.hidden=YES;
        }
    }
    
    [footerView.agreementBtn addTarget:self action:@selector(agreementAction:) forControlEvents:UIControlEventTouchUpInside];
    [footerView.facebookLoginBtn addTarget:self action:@selector(thirdPartyLogin:) forControlEvents:(UIControlEventTouchUpInside)];
    [footerView.wechatLoginBtn addTarget:self action:@selector(thirdPartyLogin:) forControlEvents:(UIControlEventTouchUpInside)];
    return footerView;
}



-(void)agreementAction:(UIButton *)sender {
    
    MYAgreementVC *agreementVC = [MYAgreementVC new];
    [self.navigationController pushViewController:agreementVC animated:true];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 122;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 24;
}

#pragma mark - WXApiDelegate
- (void)onReq:(BaseReq *)req
{
    NSLog(@"1");
}

- (void)onResp:(BaseResp *)resp
{
    NSLog(@"2");
}


#pragma mark - UITableViewDelegate, UITableViewDataSource end
-(void)selectOperateTypeAction:(UIButton *)sender {

    if ([sender.currentTitle isEqualToString:kYQLS(@"帐号登录")]) {
        self.selectOperateType = 2;
    }else if ([sender.currentTitle isEqualToString:kYQLS(@"手机号登录")]) {
        self.selectOperateType = 1;
        [self.listTableView reloadData];
        MYLoginBaseTextFieldPhoneCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        phoneCell.textField.delegate = self;
        MYLoginBaseTextFieldCodeCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        codeCell.textField.delegate = self;
        [self.codeButton addTarget:self action:@selector(sendCodeClick:) forControlEvents:UIControlEventTouchUpInside];
    }else if ([sender.currentTitle isEqualToString:kYQLS(@"邮箱注册")]) {
        [self changeOperateType];
        self.selectOperateType = 2;
        self.codeButton.enabled = YES;
        [self.codeButton addTarget:self action:@selector(sendCodeClick:) forControlEvents:UIControlEventTouchUpInside];
    }else if ([sender.currentTitle isEqualToString:kYQLS(@"手机号注册")]) {
        [self changeOperateType];
        self.selectOperateType = 1;
        self.codeButton.enabled = YES;
        [self.codeButton addTarget:self action:@selector(sendCodeClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.listTableView reloadData];
}

-(void)changeOperateType {
    [self.codeTimer stop];
    self.codeTextField.text = @"";
    self.codeButton.enabled = YES;
    [self.codeButton setTitle:kYQLS(@"发送验证码") forState:(UIControlStateNormal)];
    [self.codeButton addTarget:self action:@selector(sendCodeClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setShowType:(LoginOrRegisterType)showType {
    _showType = showType;
    self.selectOperateType = 1;
    [self.listTableView reloadData];
}

-(void)loginOrRegisterAction:(UIButton *)sender {

    if ([sender.currentTitle isEqualToString:kYQLS(@"登录")]) {//跟这里没关系
        [self loginOnHttpApi:self.showType];

    }else if([sender.currentTitle isEqualToString:kYQLS(@"注册")]){
        [self loginOnHttpApi:self.showType];

    }
}
-(void)thirdPartyLogin:(UIButton *)sender {
    NSString *arlStr = @"";
    if (sender.tag == 11100) {
        arlStr = kYQLS(@"即将跳转到脸书");
    }else{
        arlStr = kYQLS(@"即将跳转到微信");
    }
    
    QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:arlStr message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
//    alert.alertTitleAttributes = @{NSForegroundColorAttributeName:HexColor(0x7F7F7F),NSFontAttributeName:kSystemMedium(17)};
    [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"取消") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
//        [self.navigationController dismissViewControllerAnimated:true completion:nil];
    }]];
    alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
    
    [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"打开") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (sender.tag == 11100) {
             FBSDKLoginManager *manager=[[FBSDKLoginManager alloc] init];
            [manager logOut];
            [manager logInWithPermissions:@[@"public_profile",@"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
                if (!error) {
                    if (!result.isCancelled) {
                        [FBSDKProfile loadCurrentProfileWithCompletion:^(FBSDKProfile * _Nullable profile, NSError * _Nullable error) {
                            NSURL * imageURL=[profile imageURLForPictureMode:FBSDKProfilePictureModeNormal size:CGSizeMake(180, 180)];
                            NSString *url=@"/api/facebook/login";
                            NSMutableDictionary *parameters=[NSMutableDictionary dictionary];
                            [parameters setObject:profile.userID forKey:@"fbUserId"];
                            [parameters setObject:profile.firstName forKey:@"firstName"];
                            if (profile.middleName) {
                                [parameters setObject:profile.middleName forKey:@"middleName"];
                            }
                            
                            [parameters setObject:profile.lastName forKey:@"lastName"];
                            [parameters setObject:profile.name forKey:@"name"];
                            [parameters setObject:[imageURL absoluteString] forKey:@"headImg"];
                            [YQPNetWorkingManager sendPostRequest:url parameters:parameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
                               
                                if (responseObject.code == 0) {
                                                   YQPLoginModel *account = [YQPLoginModel AccountStatusWithDict:responseObject.data];
                                                   [YQPUserTool saveAccount:account];
                                                   YQMYTabBarBaseViewController *tabBarVC = [[YQMYTabBarBaseViewController alloc] init];
                                    [UIApplication sharedApplication].keyWindow.rootViewController=tabBarVC;
                                }
                                else
                                {
                                     kMBMesHUD(responseObject.msg)
                                }
                            } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
                                kMBMesHUD(error);
                            }];
                        }];
                    }
                }
            }];
        }
        else
        {
            SendAuthReq* req =[[SendAuthReq alloc]init];
            req.scope = @"snsapi_userinfo";
            req.state = @"123";
            //第三方向微信终端发送一个SendAuthReq消息结构
            [WXApi sendReq:req completion:^(BOOL success) {

            }];
        }
          
    }]];
    alert.alertButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
    [alert showWithAnimated:YES];
}



#pragma mark - 登录接口
- (void)loginOnHttpApi:(LoginOrRegisterType)showType
{
//    YQMYTabBarBaseViewController *tabBarVC = [[YQMYTabBarBaseViewController alloc] init];
//    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVC;
//    return;
    MYLoginBaseTextFieldPhoneCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    MYLoginBaseTextFieldCodeCell *codeCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    NSString *url;
    NSMutableDictionary *dic = NSMutableDictionary.new;

    if (self.showType == LoginOrRegisterTypeLogin) {
        
        if (self.selectOperateType == 1) {
            if (phoneCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入手机号")];
                return;
            }
//            else{
//                BOOL isValuate = [YQPInsureValidate validateMobile:phoneCell.textField.text];
//                if (!isValuate) {
//                    [MBProgressHUD showSuccess:@"请输入有效手机号"];
//                    return;
//                }
//            }
            if (codeCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入验证码")];
                return;
            }
            //手机验证码登录
            url = @"/api/phoneLogin";
            dic[@"mobile"] = phoneCell.textField.text;
            dic[@"code"] = codeCell.textField.text;
        }else{
//            if (phoneCell.textField.text.length == 0) {
//                [MBProgressHUD showSuccess:@"请输入用户名/邮箱"];
//                return;
//            }else{
//                BOOL isValuate = [YQPInsureValidate validateEmail:phoneCell.textField.text];
//                if (!isValuate) {
//                    [MBProgressHUD showSuccess:@"请输入有效邮箱"];
//                    return;
//                }
//            }
//            if (codeCell.textField.text.length < 6) {
//                [MBProgressHUD showSuccess:@"请输入至少6位密码"];
//                return;
//            }
            //邮箱账号密码登录
            url = kPOST_EMAIL_LOGIN_URL;
            dic[@"loginAccount"] = phoneCell.textField.text;
            NSString * password = codeCell.textField.text;
            dic[@"password"] = codeCell.textField.text;
        }
        


    }else if (self.showType == LoginOrRegisterTypeRegister){
        
        if (self.selectOperateType == 1) {
            if (phoneCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入手机号")];
                return;
            }
//            else{
//                BOOL isValuate = [YQPInsureValidate validateMobile:phoneCell.textField.text];
//                if (!isValuate) {
//                    [MBProgressHUD showSuccess:@"请输入有效手机号"];
//                    return;
//                }
//            }
            if (codeCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入验证码")];
                return;
            }
            url = kPOST_PHONE_REGIEST_URL;
            dic[@"mobile"] = phoneCell.textField.text;
            dic[@"code"] = codeCell.textField.text;
        }else{
            if (phoneCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入邮箱")];
                return;
            }else{
                BOOL isValuate = [YQPInsureValidate validateEmail:phoneCell.textField.text];
                if (!isValuate) {
                    [MBProgressHUD showSuccess:kYQLS(@"请输入有效邮箱")];
                    return;
                }
            }
            if (codeCell.textField.text.length == 0) {
                [MBProgressHUD showSuccess:kYQLS(@"请输入验证码")];
                return;
            }
            url = kPOST_verify_EMAIL_REGIEST_URL;
            dic[@"email"] = phoneCell.textField.text;
            dic[@"code"] = codeCell.textField.text;
            
        }
    }
    //http://47.75.187.115/api/yiqi-api/api/register/email  http://47.75.187.115/api/yiqi-api/api/sms
    [YQPNetWorkingManager sendPostRequest:url parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [MBProgressHUD showSuccess: responseObject.msg];
        
        if (self.showType == LoginOrRegisterTypeLogin) {
            if (responseObject.code == 0) {
                YQPLoginModel *account = [YQPLoginModel AccountStatusWithDict:responseObject.data];
                [YQPUserTool saveAccount:account];
                YQMYTabBarBaseViewController *tabBarVC = [[YQMYTabBarBaseViewController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVC;
            }
        }else if (self.showType == LoginOrRegisterTypeRegister){

            if (responseObject.code == 0) {
                MYRegisterSetPasswordVC *setPasswordVC = [[MYRegisterSetPasswordVC alloc] init];
                if (self.selectOperateType == 1) {
                    setPasswordVC.userId = responseObject.data;
                }else{
                    setPasswordVC.emailDict = dic;
                }
                
                setPasswordVC.no_userId = NO;
                [self.navigationController pushViewController:setPasswordVC animated:true];
            }
        }

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}

#pragma mark - 发送验证码
- (void)sendCodeClick:(UIButton *)button
{
    MYLoginBaseTextFieldPhoneCell *phoneCell = [self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (phoneCell.textField.text.length == 0) {
        [MBProgressHUD showSuccess:kYQLS(@"请输入账号")];
        return;
    }
    

    NSMutableDictionary *dic = NSMutableDictionary.new;
    NSString *url = @"";
    if (self.selectOperateType == 1) {
        url = kGET_CODE_SMS_international_URL;
        dic[@"phone"] = [self.mobileAreaCode stringByAppendingString:phoneCell.textField.text];
        if ([self.mobileAreaCode isEqualToString:@"86"]) {
            url = kGET_CODE_SMS_URL;
            dic[@"phone"] = phoneCell.textField.text;
        }
    }else{
        url = kGET_EMAIL_SEND_URL;
        dic[@"email"] = phoneCell.textField.text;
    }

    [YQPNetWorkingManager sendGetRequest:url parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            [MBProgressHUD showSuccess:kYQLS(@"发送成功")];
            [self.codeTimer start];
        }else{
            [MBProgressHUD showSuccess:responseObject.msg];
        }
        //codeCell.textField.text = responseObject.data;
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}

-(void)selectPhoneAreaCode {
    [self.view endEditing:true];
    ws(self);
    [AreaCodeModel getAreaCode:^(NSArray<AreaCodeModel *> * codeModelArr) {
        NSMutableArray *localeArr = [NSMutableArray array];
        NSMutableArray *localeCodeArr = [NSMutableArray array];
        for (AreaCodeModel *codeModel in codeModelArr) {
            NSString * showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.zh,codeModel.code];
            if ([[[ZBLocalized sharedInstance] currentLanguage] isEqualToString:@"en"]) {
                showTitle = [NSString stringWithFormat:@"%@ +%@",codeModel.en,codeModel.code];
            }
            
            
            [localeArr addObject:showTitle];
            [localeCodeArr addObject:codeModel.code];
        }
        
        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:localeArr.copy defaultSelValue:self.defaultLocale isAutoSelect:NO themeColor:kAPPThemeColor resultBlock:^(id selectValue) {
            self.defaultLocale = selectValue;
            MYLoginBaseTextFieldPhoneCell *cell = (MYLoginBaseTextFieldPhoneCell *)[self.listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            
            NSInteger index = [localeArr indexOfObject:selectValue];
            weakself.mobileAreaCode = localeCodeArr[index];
            
            cell.leftLb.text = [NSString stringWithFormat:@"+%@",weakself.mobileAreaCode];
            [weakself.listTableView reloadData];
        } cancelBlock:^{
            
        }];
        
    }];
}

#pragma mark 计时器KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"time"]) {
        NSInteger seconds = [[change objectForKey:@"new"] integerValue];
        NSString *time = [NSString stringWithFormat:@"%zdS",60-seconds];
        self.codeButton.enabled = NO;
        [self.codeButton setTitle:time forState:UIControlStateDisabled];
        
        if ([time isEqualToString:@"0S"]) {
            [self.codeTimer stop];
            self.codeButton.enabled = YES;
            [self.codeButton setTitle:kYQLS(@"重新获取") forState:(UIControlStateNormal)];
            [self.listTableView reloadData];
        }
    }
}

#pragma mark-- lazy
- (Calculagraph *)codeTimer {
    if (!_codeTimer) {
        _codeTimer = [[Calculagraph alloc] init];
        [_codeTimer addObserver:self forKeyPath:@"time" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _codeTimer;
}
#pragma mark-- lazy
- (void)dealloc {
    [self.codeTimer removeObserver:self forKeyPath:@"time"];
}
@end
